import { 
  AmbientLight,
  BufferGeometry,
  AxesHelper,
  Color, 
  CubicBezierCurve, 
  CubicBezierCurve3, 
  LineBasicMaterial, Mesh, MeshBasicMaterial, 
  OrthographicCamera, PerspectiveCamera, PlaneBufferGeometry, 
  Scene, ShaderMaterial, Vector3, WebGLRenderer, Line 
} from "three"
import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'

const scene = new Scene()
const renderer = new WebGLRenderer({
  antialias: true
})
renderer.setClearColor(0x000000)
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

const camera = new PerspectiveCamera(45, window.innerWidth/window.innerHeight, 0.1, 1000)
camera.position.set(40, 30, 20)
camera.lookAt(0, 0, 0)

const plane = new PlaneBufferGeometry(2, 3)

// 片段着色器
const fragmentShader = `
#include <common>

uniform float time;
// 接收指定颜色
uniform vec3 iColor;

void main() {
  float start = time;
  float end = start + 20.0;

  float opacity = 0.2;

  if (gl_FragCoord.x > 1000.0 && gl_FragCoord.x < 1200.0) {
    opacity = 1.0;
  }
  
  // if (gl_FragCoord.x > start && gl_FragCoord.x < end) {
  //   opacity = 1.0;
  // }

  gl_FragColor = vec4(iColor, opacity);
}
`

// 顶点着色器
const vertexShader = `
#include <common>

void main() {
  vec3 posChanged = position;
  gl_Position = projectionMatrix * modelViewMatrix * vec4(posChanged,1.0);
}
`

const uniforms = {
  time: { value: -1.0 },
  // 随机产生颜色
  iColor: { value: new Color(0xffffff) },
}
const material = new ShaderMaterial({
  transparent: true,
  // 片段着色器
  fragmentShader,
  // 顶点着色器
  vertexShader,
  uniforms
})
// scene.add(new Mesh(plane, material))

scene.add(new AmbientLight(0xffffff))
// 添加坐标系，方便理解
const axes = new AxesHelper(20)
scene.add(axes)

const curve = new CubicBezierCurve3(
  new Vector3(-10, 0, 0),
  new Vector3(-10, 10, 0),
  new Vector3(10, 10, 0),
  new Vector3(10, 0, 0),
)
const points = curve.getPoints(50)
console.log(points)

const geom = new BufferGeometry().setFromPoints(points)
const material2 = new LineBasicMaterial({ color: 0xffff00 })
const flyLine = new Line(geom, material)
flyLine.position.set(0, 0, 0)
scene.add(flyLine)

const trackballControls = new TrackballControls(camera, renderer.domElement)

function render(time: number) {
  time *= 0.001
  trackballControls.update()

  requestAnimationFrame(render)
  renderer.render(scene, camera)
}

requestAnimationFrame(render)